package com.itlong.cloud.controller.old;

import com.itlong.cloud.POJO.DTO.smartcard.*;
import com.itlong.cloud.POJO.PO.DeviceElevatorFloorConfigPO;
import com.itlong.cloud.POJO.PO.ProjectPO;
import com.itlong.cloud.POJO.VO.property.PropertyEquipGetVO;
import com.itlong.cloud.POJO.VO.smartcard.SmartCardOldDeviceInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.PropertyEquipTypeEnum;
import com.itlong.cloud.enumerate.oldapp.Code;
import com.itlong.cloud.enumerate.oldapp.Message;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.smartcard.ISmartCardOldDeviceServiceClient;
import com.itlong.cloud.user.smartcard.ISmartCardOldUserInfoServiceClient;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <desc>
 *      旧一卡通_设备模块。
 * <desc/>
 *
 * @createDate 2017/11/22.
 */
@RestController
@RequestMapping("/device/deviceInfo")
public class SmartCardOldDeviceController {

    private static final Logger LOG = LoggerFactory.getLogger(SmartCardOldDeviceController.class);

    //旧一卡通_设备模块更新楼层对应表
    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    ISmartCardOldDeviceServiceClient iSmartCardOldDeviceServiceClient;

    //旧一卡通用户模块接口
    @Autowired
    ISmartCardOldUserInfoServiceClient iSmartCardOldUserInfoServiceClient;

    //设备服务接口
    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;


    /**
     * <desc>
     *      更新电梯楼层对应表。
     * <desc/>
     *
     * @param  saveDTO 请求参数
     * @return
     * @author shengen.T
     * @createDate 2017/11/22
     */
    @LoggerInfo(operateDesc = LogDescConstant.UPDATE_OLDSMARTCARD_FLOORCONFIG_LOG_DESC)
    @ResponseBody
    @RequestMapping(path = "/manage/editFloorConfig",method = RequestMethod.POST)
    public Message updateFloorConfig(SmartCardOldDeviceInfoDTO saveDTO){
        Message message;
        try {
            //判断用户名
            if(!PlatformConstants.OLD_SMARTCARD_LOGIN_USER.equals(saveDTO.getMyUserName())){
                return new Message(Code.LOGIN_ERROR);
            }
            //判断楼层标识
            if(StringUtils.isBlank(saveDTO.getNaturalFloor())){
                return new Message(Code.NOT_PARAM);
            }
            //判断楼层名称
            if(StringUtils.isBlank(saveDTO.getLogicalFloor())){
                return new Message(Code.NOT_PARAM);
            }

            //判断设备唯一编号
            if(StringUtils.isBlank(saveDTO.getDeviceUnique())){
                return new Message(Code.NOT_PARAM);
            }
            Integer reslut = iSmartCardOldDeviceServiceClient.updateFloorConfig(saveDTO);
            if(reslut<1){
               return new Message(Code.ERROR);
            }
            message = new Message(Code.SUCCESS);
        }catch (Exception e){
            throw new DataAccessException("【旧一卡通update】更新楼层对应表信息失败", e);
        }
        return message;
    }


     /**
      * <desc>
      *      旧_获取设备列表。
      * <desc/>
      *
      * @param pageDTO 查询设备列表参数
      * @return
      * @author shengen.T
      * @createDate 2017-12-04
      */
     @LoggerInfo(operateDesc = "旧_获取设备列表")
     @ResponseBody
     @RequestMapping(path = "/manage/list",method = RequestMethod.POST)
     public Message getDeviceList(SmartCardOldGetDevicesPageDTO pageDTO){
         Message message;
         try {
             //判断用户名
             if(!PlatformConstants.OLD_SMARTCARD_LOGIN_USER.equals(pageDTO.getMyUserName())){
                 return new Message(Code.LOGIN_ERROR);
             }
             //判断项目编号
             if (StringUtils.isBlank(pageDTO.getProjectId()) || !pageDTO.getProjectId().matches("[0-9]{8}")) {
                 LOG.info("【旧_一卡通】获取设备列表_项目编号非法】" + pageDTO.getProjectId());
                 return new Message(Code.SDK_PROJECTID_ERR,"项目编号不合法");
             }
             //判断设备类型
             Integer deviceType = StringHandlerUtil.strToIntDef(pageDTO.getDeviceType(),-1);
             if((deviceType!= PropertyEquipTypeEnum.ELEVATOR.getType())&&(deviceType!= PropertyEquipTypeEnum.ENTRANCE.getType())){
                 return new Message(Code.ERROR,"设备类型不合法");
             }
             Page<SmartCardOldDeviceInfoVO> pageVO = iSmartCardOldDeviceServiceClient.getDevicePage(pageDTO);
             Map<String,Object> map =  new HashMap<>();
             map.put("totalNumber",pageVO.getPage().getTotalNumber());
             map.put("deviceInfos",pageVO.getRows());
             message = new Message(Code.SUCCESS,map);
         }catch (Exception e){
             throw new DataAccessException("【旧一卡通getPage】获取设备列表信息失败", e);
         }
         return message;
     }

      /**
       * <desc>
       *      增加设备信息。
       * <desc/>
       *
       * @param  myUserName 登录用户
       * @param  token  凭证
       * @param  deviceJson 设备信息
       * @return
       * @author shengen.T
       * @createDate 2017-12-10
       */
    @LoggerInfo(operateDesc = "旧_增加设备信息")
    @ResponseBody
    @RequestMapping(path = "/manage/add",method = RequestMethod.POST)
    public Message addDeviceInfo(String myUserName,String token,String deviceJson){
        Message message;
        try{
            //判断用户名
            if(!PlatformConstants.OLD_SMARTCARD_LOGIN_USER.equals(myUserName)){
                return new Message(Code.LOGIN_ERROR);
            }
            //判断设备信息参数
            if(StringUtils.isBlank(deviceJson)){
                return new Message(Code.NOT_PARAM);
            }
            message = new Message(Code.SUCCESS);
        }catch (Exception e){
            throw new DataAccessException("【旧一卡通add】添加设备信息失败", e);
        }
        return message;
    }

     /**
      * <desc>
      *      旧一卡通_修改设备。
      * <desc/>
      *
      * @param  deviceInfo 更新参数
      * @return
      * @author shengen.T
      * @createDate 2017-12-12
      */
    @LoggerInfo(operateDesc = "旧一卡通_修改设备")
    @ResponseBody
    @RequestMapping(path = "/manage/update",method = RequestMethod.POST)
    public Message updateDeviceInfo(SmartCardOldUpdateDeviceInfoDTO deviceInfo){
        Message message;
        try {
            //判断用户名
            if(!PlatformConstants.OLD_SMARTCARD_LOGIN_USER.equals(deviceInfo.getMyUserName())){
                return new Message(Code.LOGIN_ERROR);
            }
            //判断设备唯一标识
            if(StringUtils.isBlank(deviceInfo.getDeviceUnique())){
                return new Message(Code.DEVICE_UNIQUE_EMPTY_ERR);
            }
            //判断设备名称
            if(StringUtils.isBlank(deviceInfo.getDeviceName())){
                return new Message(Code.DEVICE_NAME_EMPTY_ERR);
            }
            //获取设备信息
            boolean resFlag=false;
            PropertyEquipGetVO equipGetVO= iPropertyEquipServiceClient.getByDeviceUnique(deviceInfo.getDeviceUnique());
            if(equipGetVO==null){  //如果设备不存在则添加新设备
                String deviceUnique = deviceInfo.getDeviceUnique();
                String deviceId = deviceUnique.substring(9, 13);
                deviceInfo.setDeviceId(deviceId);
                String deviceType = deviceUnique.substring(8, 9);
                deviceInfo.setDeviceType(StringHandlerUtil.strToIntDef(deviceType,-1));
                deviceInfo.setProjectId(deviceUnique.substring(0,8));
                //新增设备需要添加楼层对应表
                deviceInfo.setElevatorFloorConfigPOList(getElevatorFloorConfigList(deviceUnique));
                resFlag = iSmartCardOldDeviceServiceClient.addDeviceInfo(deviceInfo);

            }else {
                deviceInfo.setDeviceId(equipGetVO.getDeviceId());
                deviceInfo.setDeviceType(equipGetVO.getDeviceType());
                deviceInfo.setProjectId(equipGetVO.getProjectId());
                resFlag = iSmartCardOldDeviceServiceClient.updateDeviceInfo(deviceInfo);

            }
            if(!resFlag){
               return new Message(Code.ERROR);
            }
            message = new Message(Code.SUCCESS);
        }catch (Exception e){
            throw new DataAccessException("【旧一卡通update】更新设备信息失败",e);
        }
        return message;
    }

    /**
     * <desc>
     *      获取电梯楼层对应表数据。
     * <desc/>
     *
     * @param  deviceUnique
     * @return
     * @author shengen.T
     * @createDate 2017-12-12
     */
    private List<DeviceElevatorFloorConfigPO>  getElevatorFloorConfigList (String deviceUnique) throws Exception{
        List<DeviceElevatorFloorConfigPO> addFloorConfigList = new ArrayList<>();
        for (int i=1;i<113;i++){
            DeviceElevatorFloorConfigPO floorConfigPO = new DeviceElevatorFloorConfigPO();
            floorConfigPO.setLogicalFloor(String.format("%s%s",i,"层"));
            floorConfigPO.setDeviceUnique(deviceUnique);
            floorConfigPO.setNaturalFloor(String.format("%s",i));
            floorConfigPO.setStatus(1);
            floorConfigPO.setCreateTime(new Date());
            addFloorConfigList.add(floorConfigPO);
        }
         return addFloorConfigList;
    }


    /**
     * <desc>
     *      旧一卡通_为用户授权门禁
     * <desc/>
     *
     * @param authDoorDTO 门禁权限数据
     * @return 返回影响行数
     * @author chunjian.G
     * @createDate 2017/11/3
     */
    @LoggerInfo(operateDesc = LogDescConstant.OLDSMARTCARD_AUTH_DOOR_LOG_DESC)
    @ResponseBody
    @RequestMapping(path = "manage/authDoor", method = RequestMethod.POST)
    public Message authDoor(SmartCardOldAuthDoorDTO authDoorDTO){
        try {
            //合法性判断
            if (null == authDoorDTO){
                return new Message(Code.NOT_PARAM);
            }
            if (StringUtils.isBlank(authDoorDTO.getProjectId())){
                return new Message(Code.PARAM_ERR);
            }
            if (StringUtils.isBlank(authDoorDTO.getAuthPhoneNo())){
                return new Message(Code.PHONE_NO_INVALID_ERR);
            }
            List<String> authUniques = StringHandlerUtil.splitStringList(authDoorDTO.getDeviceUniques());
            if (!checkDevUniquesValid(authUniques, authDoorDTO.getProjectId(), PropertyEquipTypeEnum.ENTRANCE.getType())){
                return new Message(Code.PARAM_ERR);
            }

            //获取项目信息
            ProjectPO projectPO = iOperateProjectServiceClient.getOneProject(authDoorDTO.getProjectId());
            if (projectPO == null){
                return new Message(Code.PROJECT_NOT_EXIST);
            }

            //检查设备是否存在，不存在则添加
            List<String> existUniques = iSmartCardOldDeviceServiceClient
                    .getDeviceUniques(authDoorDTO.getProjectId(), PropertyEquipTypeEnum.ENTRANCE.getType());
            if (!existUniques.containsAll(authUniques)){
                //去除已有设备
                authUniques.removeAll(existUniques);
                iSmartCardOldDeviceServiceClient.addDefaultDevices(authUniques,
                        PropertyEquipTypeEnum.ENTRANCE.getType(), authDoorDTO.getProjectId());
            }

            //处理数据
            authDoorDTO.setHandledDoorAuth(this.getDeviceAuthString(authDoorDTO.getDeviceUniques(),
                    PlatformConstants.ENTRANCE_AUTHNUM,
                    PlatformConstants.ENTRANCE_NOAUTHNUM,
                    PlatformConstants.MAX_ENTRANCE_DEVICEID));
            //授权门禁
            Integer result =  iSmartCardOldUserInfoServiceClient.authDoor(authDoorDTO, projectPO.getIsSmartCommunity());

            return new Message(Code.SUCCESS);
        }catch (Exception e){
            throw new DataAccessException("【旧一卡通authDoor】为用户授权门禁失败", e);
        }
    }

    /**
     * <desc>
     *      旧一卡通_为用户授权电梯
     * <desc/>
     *
     * @param authFloorDTO 电梯权限数据
     * @return 返回影响行数
     * @author  chunjian.G
     * @createDate 2017/11/3
     */
    @LoggerInfo(operateDesc = LogDescConstant.OLDSMARTCARD_AUTH_FLOOR_LOG_DESC)
    @ResponseBody
    @RequestMapping(path = "manage/authFloor", method = RequestMethod.POST)
    public Message authFloor(SmartCardOldAuthFloorDTO authFloorDTO){
        try {
            //合法性判断
            if (null == authFloorDTO){
                return new Message(Code.NOT_PARAM);
            }
            if (StringUtils.isBlank(authFloorDTO.getProjectId())){
                return new Message(Code.PARAM_ERR);
            }
            if (StringUtils.isBlank(authFloorDTO.getAuthPhoneNo())){
                return new Message(Code.PHONE_NO_INVALID_ERR);
            }

            List<String> authUniques = StringHandlerUtil.splitStringList(authFloorDTO.getDeviceUniques());
            if (!checkDevUniquesValid(authUniques, authFloorDTO.getProjectId(), PropertyEquipTypeEnum.ELEVATOR.getType())){
                return new Message(Code.PARAM_ERR);
            }

            //获取项目信息
            ProjectPO projectPO = iOperateProjectServiceClient.getOneProject(authFloorDTO.getProjectId());
            if (projectPO == null){
                return new Message(Code.PROJECT_NOT_EXIST);
            }

            //检查设备是否存在，不存在则添加
            List<String> existUniques = iSmartCardOldDeviceServiceClient
                    .getDeviceUniques(authFloorDTO.getProjectId(), PropertyEquipTypeEnum.ELEVATOR.getType());
            if (!existUniques.containsAll(authUniques)){
                //去除已有设备
                authUniques.removeAll(existUniques);
                iSmartCardOldDeviceServiceClient.addDefaultDevices(authUniques,
                        PropertyEquipTypeEnum.ELEVATOR.getType(), authFloorDTO.getProjectId());
            }

            //处理数据
            authFloorDTO.setHandledDeviceAuth(this.getDeviceAuthString(authFloorDTO.getDeviceUniques(),
                    PlatformConstants.ELEVATOR_AUTHNUM,
                    PlatformConstants.ELEVATOR_NOAUTHNUM,
                    PlatformConstants.MAX_ELEVATOR_DEVICEID));
            authFloorDTO.setHandledFloorAuth(authFloorDTO.getFloorAuth());
            //授权电梯
            Integer result =  iSmartCardOldUserInfoServiceClient.authFloor(authFloorDTO, projectPO.getIsSmartCommunity());

            return new Message(Code.SUCCESS);
        }catch (Exception e){
            throw new DataAccessException("【旧一卡通authFloor】为用户授权电梯失败", e);
        }
    }

    /**
     * <desc>
     *      检测设备唯一码合法性
     * <desc/>
     *
     * @param
     * @return
     * @author Chunjian.G
     * @createDate 2017-12-18
     */
    private boolean checkDevUniquesValid(List<String> devUniques, String projectId, Integer devType){
        if (devUniques != null && !devUniques.isEmpty()){
            for (String devUnique: devUniques){
                if (devUnique.length() != 13){
                    return false;
                }
                if (!projectId.equals(StringHandlerUtil.getProjectIdByDeviceUnique(devUnique))){
                    return false;
                }
                if (!devType.equals(StringHandlerUtil.getDeviceTypeByDeviceUnique(devUnique))){
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * <desc>
     *      用户设备权限-获取授权设备信息(有权限的设备自然数字符串，如电梯00011011...、门禁78877..77等)
     * <desc/>
     *
     * @param deviceUniques 设备唯一码,英文逗号拼接
     * @param authNum 有权限设备自然数字符串标识
     * @param noAuthNum 无权限设备自然数字符串标识
     * @param deviceCount 设备总数
     * @return String
     * @author  chunjian.G
     * @createDate 2017/10/10
     */
    private String getDeviceAuthString(
            String deviceUniques,
            String authNum,
            String noAuthNum,
            int deviceCount) {
        if(StringUtils.isBlank(deviceUniques)) {
            return null;
        }
        StringBuffer deviceAuthBuffer = new StringBuffer(deviceCount);
        for(int i = 0;i < deviceCount;i++) {
            deviceAuthBuffer.append(noAuthNum);
        }
        String[] devUniques = StringHandlerUtil.splitString(deviceUniques);
        for (String devUnique : devUniques) {
            if (StringUtils.isNotBlank(devUnique)) {
                int devId = StringHandlerUtil.strToIntDef(StringHandlerUtil.getDeviceIdByDeviceUnique(devUnique), 0);
                if (devId > 0){
                    deviceAuthBuffer.setCharAt(devId - 1, authNum.charAt(0));
                }
            }
        }
        return deviceAuthBuffer.toString();
    }
}
